/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.service.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 *
 * @author ECH
 */
public class FourSQ {

    private String QUERY_URL = "https://api.foursquare.com/v2/venues/${venue-id}/tips?sort=recent&oauth_token=${oauth-token}&v=20140120";
    private String CLIENT_ID = "ML2DEUK5TVCJIAXQR23ABT1VYGMHPJZOAKDH31HY4USHGYIM";
    private String CLIENT_SECRET = "MT25LXV1Z1FA2ANQ3ZNSEPRLFLQAKCRNAOKSZXDJICEKVFVC";
    private String OAUTH_TOKEN = "Y0J0JDC2H12BMMUSBF4R354RNVXRFUDTCTLOOMVPMNJ4VP4Q";

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
        
            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonText );
            return json;
        } finally {
            is.close();
        }
    }

    public List<FourSQTip> readVenueTips(String venueID) {
        List<FourSQTip> venueTips = new ArrayList<FourSQTip>();
        try {
            String query = QUERY_URL.replaceFirst("\\$\\{venue-id\\}", venueID).replaceFirst("\\$\\{oauth-token\\}", OAUTH_TOKEN);
            JSONObject json = readJsonFromUrl(query);
            Object[] objArr = json.getJSONObject("response").getJSONObject("tips").getJSONArray("items").toArray();
            
            for (int i = 0; i < objArr.length; i++) {
                JSONObject tip = (JSONObject)objArr[i]; 
                JSONObject user = null;
                JSONObject photo = null;   
                
                String text = "";
                String canonicalUrl = "";
                String firstName = "";
                String lastName = "";
                
                String photoPrefix = "";
                String photoSuffix = "";
                
                try { user = tip.getJSONObject("user");  } catch (Exception e) { }
                try { photo = user.getJSONObject("photo");   } catch (Exception e) { }
                
                try { text = tip.getString("text"); } catch (Exception e) { }
                try { canonicalUrl = tip.getString("canonicalUrl"); } catch (Exception e) { }
                try { firstName = user.getString("firstName"); } catch (Exception e) { }
                try { lastName = user.getString("lastName"); } catch (Exception e) { }
                
                if (photo != null) {
                    try { photoPrefix = photo.getString("prefix"); } catch (Exception e) { }
                    try { photoSuffix = photo.getString("suffix");  } catch (Exception e) { }
                }
                
                FourSQTip foursqTip = new FourSQTip();
                foursqTip.setText(text);
                foursqTip.setCanonicalUrl(canonicalUrl);
                foursqTip.setFirstName(firstName);
                foursqTip.setLastName(lastName);
                foursqTip.setPhotoPrefix(photoPrefix);
                foursqTip.setPhotoSufix(photoSuffix); 
                
                venueTips.add(foursqTip);
            }
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }       
        return venueTips;
    }
    
    public static void main(String[] args) throws IOException, JSONException {
        FourSQ fsq = new FourSQ();
        List<FourSQTip> tips = fsq.readVenueTips("4cc130eff82ebfb7f6077091");
        for (FourSQTip tip : tips) {
            System.out.println("CX: " + tip.getText());
        }
    }

}
